<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if(!class_exists('Api_hd_invitation')){
    class Api_hd_invitation extends CI_Controller {

        protected $_action = '';

        protected $_distance = 325;

        private $_source = '';
        private $_type = '';

        public function __construct(){
            parent::__construct();
            $this->load->model('Apilogmodel','m_api_log');
            $this->load->model('Usermodel','m_user');
            $this->load->model('Appmodel','m_app');
            $this->load->model('Hdinvitationcustomermodel','m_customer');
            $this->load->model('Hdinvitationlotterytimemodel','m_lottery_time');
            $this->load->model('configmodel','m_config');
            $this->load->database();

            $this->_source = $this->input->post('source');
            // $game_deadline = $this->m_config->getConfig(HD_INVITATION_DEADLINE);
            // if(!empty($game_deadline) && strtotime($game_deadline) < time()) {
            //     $this->response->setDetail('活动已结束!');
            //     $this->response->responseExit();
            // }
        }

        public function __destruct() {
            // $this->session->unset_userdata($this->_action);
            $customer = $this->session->userdata('hd_invitation_customer');
            $info = $this->input->post();
            $result = $this->response->getResult();
            @$this->m_api_log->createApiLog(array(
                'ip_address' => $this->input->ip_address(),
                'customer_id' => empty($customer) ? 0 :  $customer['customer_id'],
                'request_uri' => $_SERVER['REQUEST_URI'],
                'post_data' => json_encode($info,JSON_UNESCAPED_UNICODE),
                'result_data' => json_encode($result,JSON_UNESCAPED_UNICODE),
                'api_log_time_create' => NOW,
                'ua' => empty($_SERVER['HTTP_USER_AGENT']) ? '' : $_SERVER['HTTP_USER_AGENT'],
                // 'terminal' => TERMINAL_WEIXIN,
            ));

            $this->db->close();
        }

        private function _checkType() {
            $info = $this->input->post();
            $type = isset($info['type']) ? intval($info['type']) : 0;
            if($type < 1 || $type > 3) {
                $this->response->setDetail('请勿恶意访问!');
                $this->response->responseExit();
            }
            $type_key = constant('HD_INVITATION_TYPE_'.$type);
            $type_value = $this->m_config->getConfig($type_key);
            if(empty($type_value)) {
                $this->response->setDetail('未设置时间!');
                $this->response->responseExit();
            }
            $type_value = explode('|',$type_value);
            if(NOW < $type_value[0]) {
                $this->response->setDetail('活动未开始!');
                $this->response->responseExit();
            }
            if(NOW > $type_value[1]) {
                $this->response->setDetail('活动已结束!');
                $this->response->responseExit();
            }
            $this->_type = $type;
        }


        public function initCustomer() {
            $this->_checkType();
            $this->validate->setRule('openid','string');
            $this->validate->setRule('openid','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('openid_md5','string');
            $this->validate->setRule('openid_md5','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('nickname','string');
            $this->validate->setRule('nickname','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('sex','integer');
            $this->validate->setRule('sex','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('province','string');
            $this->validate->setRule('province','notnull',false);
            $this->validate->setRule('province','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('city','string');
            $this->validate->setRule('city','notnull',false);
            $this->validate->setRule('city','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('country','string');
            $this->validate->setRule('country','notnull',false);
            $this->validate->setRule('country','message',$this->lang->line('error_parameter'));
            $this->validate->setRule('headimgurl','string');
            $this->validate->setRule('headimgurl','notnull',false);
            $this->validate->setRule('headimgurl','message',$this->lang->line('error_parameter'));
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();
            $info['create_source'] = $this->_source;

            if(md5($info['openid'].FREEDOM_WAR_SALT) != $info['openid_md5']) {
                $this->response->setDetail('请勿恶意访问!');
                $this->response->responseExit();
            }
            unset($info['openid_md5']);


            $info['nickname'] = urlencode($info['nickname']);

            $customer = $this->m_customer->getCustomerByOpenid($info['openid']);
            if(!empty($customer) && $customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }
            if(empty($customer)) {
                $info['customer_time_create'] = NOW;
                $customer_id = $this->m_customer->createCustomer($info);
                if($customer_id == 0) {
                    $this->response->setDetail('初始化用户失败！请刷新页面！');
                    $this->response->responseExit();
                }
                $customer = $this->m_customer->getCustomer($customer_id);
            } else if($customer['nickname'] != $info['nickname'] || $customer['headimgurl'] != $info['headimgurl']){
                $info['customer_id'] = $customer['customer_id'];
                $this->m_customer->editCustomer($info);
                $customer = $this->m_customer->getCustomer($info['customer_id']);
            }
            $h5_type = json_decode($customer['h5_type']);
            if(!in_array($this->_type,$h5_type)) {
                $h5_type[] = $this->_type;
            }
            $this->m_customer->editCustomer(array(
                'customer_id' => $customer['customer_id'],
                'h5_type' => json_encode($h5_type),
            ));
            global $g_hd_invitation_gift_type;
            $customer['nickname'] = urldecode($customer['nickname']);
            $customer['gift_name'] = id2name($customer['gift_type'],$g_hd_invitation_gift_type);

            $this->session->set_userdata('hd_invitation_customer',$customer);

            $history = $this->m_customer->getLotteryHistoryList($customer['customer_id']);
            $history = reindexArray($history,'type');
            $customer['history'] = $history;

            $this->response->setSuccess();
            $this->response->setDetail('提交成功!');
            $this->response->setAddon(array(
                'customer' => $customer,
                'count' => 40000 + $this->m_customer->getCustomerCount(),
            ));
            $this->response->responseExit();
        }

        private function _getRandomCode() {
        	// $code = uniqid();
        	$code = '';
        	$str ='1234567890abcdefghijklmnopqrstuvwxyz';
        	$len = strlen($str);
        	for($i=0;$i<6;$i++) {
        		$code = $str[rand()%$len].$code;
        	}
        	return $code;
        }

        public function getCode() {
          if($this->input->post('hack') !== 'FREEDOM_WAR_SALT') {
            $this->response->setDetail('领取活动已结束!');
            $this->response->responseExit();
          }

            $this->_checkType();

            $this->validate->setRule('type','integer');
            if(!$this->validate->run($this->input->post(),true)){
                $this->response->setDetail($this->validate->getMessage());
                $this->response->responseExit();
            }
            $info = $this->validate->getResult();

            $customer = $this->session->userdata('hd_invitation_customer');
            if(empty($customer)) {
                $this->response->setDetail('初始化用户失败！请刷新页面重试！');
                $this->response->responseExit();
            }
            if($customer['customer_status'] == -2) {
                $this->response->setDetail('您存在恶意刷屏!');
                $this->response->responseExit();
            }

            if(!$this->m_customer->checkLotteryGiftAvailable($customer['customer_id'],$info['type'])) {
            	$this->response->setDetail('您已参与此次活动抽奖!');
                $this->response->responseExit();
            }

            $lottery_result = 0;
            $lottery_time_id=0;
            $lotteryTime = $this->m_lottery_time->getCurrentLotteryTimeRate();
            if(!empty($lotteryTime)) {
            	$lottery_time_id = $lotteryTime['lottery_time_id'];

                $baseNum = 1000000000;
	            $num = rand(1,$baseNum);

                if(!$this->m_customer->checkHasLotteryGift($customer['customer_id'])) {
                	$rate = 0;
                    for($i = 1; $i <= 9; $i++) {
                        $time_rate = floatval($lotteryTime['lottery_time_gift'.$i.'_rate']);
                        $rate += $time_rate;
                        if($lottery_result == 0 && $time_rate > 0 && $num <= $rate*$baseNum
                            && intval($lotteryTime['lottery_time_gift'.$i.'_count']) > intval($lotteryTime['lottery_time_gift'.$i.'_count_drawn'])) {
                            $lottery_result = $i;
                            break;
                        }
                    }
                }
            }

            //记录数据库
            $lottery_history_id = 0;
            $code = NULL;
            $count = 0;
            while($lottery_history_id == 0) {
                if($lottery_result > 0) $code = $this->_getRandomCode();
                $lottery_history_id = $this->m_customer->createLotteryHistory(array(
                    'customer_id' => $customer['customer_id'],
                    'lottery_time_id' => $lottery_time_id,
                    'gift_type' => $lottery_result,
                    'type' => $info['type'],
                    'lottery_time_time_create' => NOW,
                    'code' => $code,
                    'lottery_source' => $this->_source,
                ));
                $count++;
                if($count > 10) {
                    break;
                }
            }
            if($count > 10) {
                $this->response->setDetail('出了点小问题~请重试!');
                $this->response->responseExit();
            }

            $this->m_customer->updateCustomerLotteryCount($customer['customer_id']);

            $lottery_source = json_decode($customer['lottery_source']);
            if($lottery_source == NULL) {
                $lottery_source = array();
            }
            $lottery_source[] = $this->_source;
            if($lottery_result > 0) {
                $this->m_customer->editCustomer(array(
                    'customer_id' => $customer['customer_id'],
                    'gift_type' => $lottery_result,
                    'gift_code' => $code,
                	'lottery_time_id' => $lottery_time_id,
                    'customer_time_lottery' => NOW,
                    'lottery_source' => json_encode($lottery_source),
                ));
                $this->m_lottery_time->updateLotteryCountDrawn($lottery_time_id,$lottery_result);
            } else {
                $this->m_customer->editCustomer(array(
                    'customer_id' => $customer['customer_id'],
                    'lottery_source' => json_encode($lottery_source),
                ));
            }

            $customer = $this->m_customer->getCustomer($customer['customer_id']);
            $customer['nickname'] = urldecode($customer['nickname']);
            $this->session->set_userdata('hd_invitation_customer',$customer);

            global $g_hd_invitation_gift_type;
            $addon = array();
            $addon['gift_type'] = $lottery_result;
            $addon['gift_name'] = id2name($lottery_result,$g_hd_invitation_gift_type);
            $addon['gift_code'] = $code;
            $history = $this->m_customer->getLotteryHistoryList($customer['customer_id']);
            $history = reindexArray($history,'type');
            $addon['history'] = $history;

            $this->response->setSuccess();
            $this->response->setAddon($addon);
            $this->response->responseExit();
        }

        public function dbview() {
            die();
            $data['desc'] = '清除本田邀请数据';
            $data['ctrlName'] = $this->uri->rsegments[1];
            $this->load->view('zm/clear_db',$data);
        }
        public function clearDb(){
            die();
            // $this->db->query('ALTER TABLE `mpc_hd_invitation_lottery_history` ADD UNIQUE INDEX (`code`);');
            $this->db->truncate('hd_invitation_customer');
            $this->db->truncate('hd_invitation_lottery_history');
            $this->db->truncate('hd_invitation_reading_quanity');


            $this->response->setSuccess();
            $this->response->setDetail('清除成功!');
            $this->response->responseExit();
        }
    }

}
